package com.xiaotu.common.util;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;
import java.util.Map;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

/**
 * Copyright (c)2013,小土科技 All rights reserved. <core>字符串的工具类</core>
 *
 * @author Administrator
 */
public class StringUtil
{
    /**
     * 将数据集转成csv中的一行
     *
     * @param dataList 数据集
     * @return csv行字符串
     */
    public static String list2CSVLine(List<Object> dataList, String sep)
    {
        if (dataList == null || dataList.isEmpty())
            return StringUtils.EMPTY;
        StringBuffer buffer = new StringBuffer();
        String text;
        String field;
        for (Object data : dataList)
        {
            text = nullToString(data);
            if (StringUtils.isEmpty(text))
                field = sep;
            else
                field = sep + "\"" + text.replaceAll("\"", "\"\"") + "\"";
            buffer.append(field);
        }
        return buffer.toString().substring(sep.length());
    }

    public static String map2CSVLine(Map<String, Object> map, String sep,
            String... fields)
    {
        if (map == null || map.isEmpty() || fields == null || fields.length < 1)
            return null;
        StringBuffer buffer = new StringBuffer();
        String text;
        String field;
        for (String key : fields)
        {
            text = nullToString(map.get(key));
            if (StringUtils.isEmpty(text))
                field = sep;
            else
                field = sep + "\"" + text.replaceAll("\"", "\"\"") + "\"";
            buffer.append(field);
        }
        return buffer.toString().substring(sep.length());
    }

    /**
     * 判断字符串是否是空串
     *
     * @param str 待判断的字符串
     * @return
     */
    public static boolean isEmpty(Object str)
    {
        if (str == null)
        {
            return true;
        }
        else
        {
            String strObj = str.toString().toLowerCase().trim();
            if (strObj.equals("") || strObj.equals("null")
                    || strObj.equals("\"null\"") || strObj.equals("'null'"))
            {
                return true;
            }
            return false;
        }
    }

    public static String getString(String str)
    {
        if (StringUtil.isEmpty(str))
        {
            return str;
        }
        return str.replace("{", StringUtils.EMPTY).replace("}",
                StringUtils.EMPTY);
    }

    /**
     * 判断字符串不为空
     *
     * @param str
     * @return
     */
    public static boolean isNotEmpty(Object str)
    {
        if (isEmpty(str))
        {
            return false;
        }
        return true;
    }

    /**
     * 清除字符串中的空格
     *
     * @param str
     * @return
     */
    public static String removeStrSpace(String str)
    {
        if (str == null || str.equals(StringUtils.EMPTY))
        {
            return str;
        }
        Matcher matcher = Pattern.compile("\\s").matcher(str);
        return matcher.replaceAll(StringUtils.EMPTY);
    }

    /**
     * 将对象转化为字符串，如果对象为null,返回StringUtils.EMPTY
     *
     * @param obj 对象
     * @return 转化的字符串
     */
    public static String nullToString(Object obj)
    {
        return nullToString(obj, StringUtils.EMPTY);
    }

    /**
     * 将对象转化为字符串，如果对象为null,返回tip
     *
     * @param obj 对象
     * @param tip 提示信息
     * @return 转化的字符串
     */
    public static String nullToString(Object obj, String tip)
    {

        if (obj == null)
        {
            return tip;
        }

        String temp = obj.toString().trim();
        if (temp.equals(StringUtils.EMPTY) || temp.equals("null"))
        {
            return tip;
        }
        else
        {
            return temp;
        }

    }

    /**
     * 若全部为非空，则返回true
     *
     * @param values 数据
     * @return 校验结果
     */
    public static boolean allNotEmpty(String... values)
    {
        for (String val : values)
            if (StringUtils.isEmpty(val))
                return false;
        return true;
    }

    /**
     * 任意为非空，则返回true
     *
     * @param values 数据
     * @return 校验结果
     */
    public static boolean oneNotEmpty(String... values)
    {
        for (String val : values)
            if (StringUtils.isNotEmpty(val))
                return true;
        return false;
    }

    /**
     * 中文數字转阿拉伯数组【十万九千零六十 --> 109060】
     *
     * @param chineseNumber
     * @return
     * @author 雪见烟寒
     */
    public static String chineseNumber2Int(String chineseNumber)
    {
        if (RegexUtils.regexMatch(RegexUtils.REGEX_INTEGER, chineseNumber))
            return chineseNumber;
        int result = 0;
        int temp = 1;// 存放一个单位的数字如：十万
        int count = 0;// 判断是否有chArr
        char[] cnArr = new char[]{'一', '二', '三', '四', '五', '六', '七', '八',
                '九'};
        char[] chArr = new char[]{'十', '百', '千', '万', '亿'};
        for (int i = 0; i < chineseNumber.length(); i++)
        {
            boolean b = true;// 判断是否是chArr
            char c = chineseNumber.charAt(i);
            for (int j = 0; j < cnArr.length; j++)
            {// 非单位，即数字
                if (c == cnArr[j])
                {
                    if (0 != count)
                    {// 添加下一个单位之前，先把上一个单位值添加到结果中
                        result += temp;
                        temp = 1;
                        count = 0;
                    }
                    // 下标+1，就是对应的值
                    temp = j + 1;
                    b = false;
                    break;
                }
            }
            if (b)
            {// 单位{'十','百','千','万','亿'}
                for (int j = 0; j < chArr.length; j++)
                {
                    if (c == chArr[j])
                    {
                        switch (j)
                        {
                            case 0:
                                temp *= 10;
                                break;
                            case 1:
                                temp *= 100;
                                break;
                            case 2:
                                temp *= 1000;
                                break;
                            case 3:
                                temp *= 10000;
                                break;
                            case 4:
                                temp *= 100000000;
                                break;
                            default:
                                break;
                        }
                        count++;
                    }
                }
            }
            if (i == chineseNumber.length() - 1)
            {// 遍历到最后一个字符
                result += temp;
            }
        }
        return result + StringUtils.EMPTY;
    }

    /**
     * 半角转全角标点
     *
     * @param input
     * @return
     */
    public static String toSBC(String input)
    {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++)
        {
            if (isEngDoc(c[i]))
                c[i] = (char) (c[i] + 65248);
        }
        return new String(c);
    }

    /**
     * 判断是否为半角标点
     *
     * @param c
     * @return
     */
    private static boolean isEngDoc(char c)
    {
        return ((c < 48 && c > 32) || (c < 65 && c > 57) || (c < 97 && c > 90) || (c < 127 && c >
                122));
    }

    /**
     * 全角转半角标点
     *
     * @param input
     * @return
     */
    public static String toDBC(String input)
    {
        char[] c = input.toCharArray();
        for (int i = 0; i < c.length; i++)
        {
            if (c[i] == 12288)
            {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        return new String(c);
    }

    public static String urlDecode(String url)
    {
        try
        {
            return URLDecoder.decode(url, "UTF-8");
        }
        catch (UnsupportedEncodingException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * @param dataList 数据集
     * @return tmp行字符串
     */
    public static String list2TmpLine(List<Object> dataList, String sep)
    {
        if (dataList == null || dataList.isEmpty())
            return StringUtils.EMPTY;
        StringBuffer buffer = new StringBuffer();
        String text;
        String field;
        for (int i=0; i<dataList.size();i++)
        {
        	if(i==0){
        		text = nullToString("kw="+dataList.get(i));
        	}else{
        		text = dataList.get(i).toString();
        	}
           
            field = text + sep ;
            buffer.append(field);
        }
        return buffer.toString();
    }
    
    /**
     * 汉字转换位汉语拼音，英文字符不变
     * @param chines 汉字
     * @return 拼音
     */
     public static String converterToSpell(String chines){   
     	String reg = "[^\u4e00-\u9fa5 a-zA-Z]";  
         Pattern pat = Pattern.compile(reg);    
         Matcher mat = pat.matcher(chines);   
         String repickStr = mat.replaceAll("");  
         String pinyinName = "";
         char[] nameChar = repickStr.toCharArray();
         HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
         defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
         defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
         for (int i = 0; i < nameChar.length; i++) {
             if (nameChar[i] > 128) {
                 try {
                     pinyinName += PinyinHelper.toHanyuPinyinStringArray(nameChar[i], defaultFormat)[0];
                 } catch (BadHanyuPinyinOutputFormatCombination e) {
                     e.printStackTrace();
                 }
             }else{
             	pinyinName += nameChar[i];
             }
         }
         return Pattern.compile("[^a-zA-Z]").matcher(pinyinName).replaceAll("");
     }
     
     public static File getFile(String fullName) {
         checkAndMakeParentDirecotry(fullName);
         return new File(fullName);
     }

     public static void checkAndMakeParentDirecotry(String fullName) {
         int index = fullName.lastIndexOf(SepratorUtil.SEP_SLASH_EN);
         if (index > 0) {
             String path = fullName.substring(0, index);
             File file = new File(path);
             if (!file.exists()) {
                 file.mkdirs();
             }
         }
     }
     
     //去除后缀括号
     public static String removeBrackets(String str){
    	if(StringUtils.isBlank(str)){
    		return null;
    	} 
    	if((str.lastIndexOf("）")!=-1 || str.lastIndexOf(")")!=-1) && (str.lastIndexOf("（")!=-1 || str.lastIndexOf("(")!=-1)){
 			str = str.replaceAll("[(（]", "（").replaceAll("[)）]", "）");
 			str = str.substring(0, str.lastIndexOf("（"));
 			return str;
 		}else{
 			return str;
 		}
    	
     }
     
     //取出后缀括号中的内容
     public static String [] getBracketsContent(String str){
    	String[] arr = new String[2]; 
    	if(StringUtils.isBlank(str)){
    		return arr;
    	} 
    	if((str.lastIndexOf("）")!=-1 || str.lastIndexOf(")")!=-1) && (str.lastIndexOf("（")!=-1 || str.lastIndexOf("(")!=-1)){
 			str = str.replaceAll("[(（]", "（").replaceAll("[)）]", "）");
 			String title = str;
 			arr[0] = title.substring(0, str.lastIndexOf("（"));
 			String content = str;
 			arr[1] = content.substring(str.lastIndexOf("（")+1,str.length()-1);
 		}else{
 			arr[0] = str;
 			arr[1] = "其他";
 		}
    	
    	return arr;
    	
     }
     
     
     /**
      * 过滤特殊字符
      * @param str
      * @return
      */
     public static String stringFilter (String str){
         String regEx="[`~!@#$%^&*()+=|{}':;',\\[\\].·<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
         Pattern p = Pattern.compile(regEx);
         Matcher m = p.matcher(str);
         return m.replaceAll("").trim();
     }
     
     /***
      * 过滤表情相关特殊字符
      * @param str
      * @return
      */
     public static String delSpecialCharacters(String str){
     	if(null == str || StringUtils.isBlank(str)){
     		return null;
     	}
     	return str.replaceAll("[^(0-9a-zA-Z\u4e00-\u9fa5\\p{P}\r\n )]", "");
     }
     
     /***
      * 判断target是否只匹配regex
      * @param target
      * @param regex
      * @return
      */
     public static boolean matchesStr(String target,String regex){
    	 return Pattern.matches(regex, target);
     }
     
     public static void main(String[] args) {
    	 System.out.println(matchesStr("","[0-9]{0,}[-]{0,}[0-9]{0,}"));
     }
     
}
